package Day012_多线程2.ZuoYe;

import java.util.concurrent.CountDownLatch;

/**
 * @author zhangyan
 * @date 2020/4/30 17:38
 */
public class Test3_4 {
    public static void main(String[] args) {

        //创建对象
        CountDownLatch cdl = new CountDownLatch(1);
        //创建两条线程
        MyRunnableA mrA = new MyRunnableA(cdl);
        Thread t1 = new Thread(mrA);
        t1.start();

        MyRunnableB mrB = new MyRunnableB(cdl);
        Thread t2 = new Thread(mrB);
        t2.start();
    }
}

class MyRunnableA implements Runnable {
    //构造成员变量
    CountDownLatch cdl;

    public MyRunnableA(CountDownLatch cdl) {
        this.cdl = cdl;
    }

    @Override
    public void run() {
        System.out.println("开始计算");

        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("计算完毕");
    }
}

class MyRunnableB implements Runnable {

    CountDownLatch cdl;

    public MyRunnableB(CountDownLatch cdl) {
        this.cdl = cdl;
    }

    @Override
    public void run() {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        System.out.println("计算1-100的和为:" + sum);
        cdl.countDown();
    }
}
